package com.newdjk.newdoctor.ui;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.Gson;
import com.newdjk.newdoctor.BuildConfig;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.base.BaseAppcompatActivity;
import com.newdjk.newdoctor.constants.AppConfig;
import com.newdjk.newdoctor.constants.EnvironmentManager;
import com.newdjk.newdoctor.dialog.LoadDialog;
import com.newdjk.newdoctor.dialog.SelectedIDcardDialog;
import com.newdjk.newdoctor.dialog.SelectedPictureDialog;
import com.newdjk.newdoctor.entity.ChooseImgEntity;
import com.newdjk.newdoctor.entity.IDcardEntity;
import com.newdjk.newdoctor.entity.KeyStorageEntity;
import com.newdjk.newdoctor.entity.MessageEvent;
import com.newdjk.newdoctor.entity.ScanCodeEntity;
import com.newdjk.newdoctor.entity.SendGoodsEntity;
import com.newdjk.newdoctor.entity.ServiceIndrocutionEntity;
import com.newdjk.newdoctor.entity.ServicePayWxInfo;
import com.newdjk.newdoctor.entity.ShareWXEntity;
import com.newdjk.newdoctor.entity.ShowImageEntity;
import com.newdjk.newdoctor.entity.UploadImgSuccessEntity;
import com.newdjk.newdoctor.utils.Base64Util;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.Event;
import com.newdjk.newdoctor.utils.IdcardRecognise;
import com.newdjk.newdoctor.utils.LocationUtils;
import com.newdjk.newdoctor.utils.LogOutUtil;
import com.newdjk.newdoctor.utils.NotificationUtils;
import com.newdjk.newdoctor.utils.PDFviewUtils;
import com.newdjk.newdoctor.utils.RxBus;
import com.newdjk.newdoctor.utils.SpUtils;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.wxapi.WXPayEntryActivity;
import com.newdjk.okhttp.RetrofitFactory;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class WebViewActivity extends BaseAppcompatActivity implements IWXAPIEventHandler, View.OnClickListener {


    private static final String TAG = "WebViewActivity";
    @BindView(R.id.test_bridge_webView)
    BridgeWebView testBridgeWebView;
    @BindView(R.id.view_cover)
    View viewCover;
    @BindView(R.id.bu_share)
    Button buShare;
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_center_title)
    TextView tvCenterTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.action_bar_container)
    FrameLayout actionBarContainer;

    private Gson mGson;
    private int type;
    private String mUrl;
    private CallBackFunction mFunction;
    private SelectedPictureDialog mSelectedPictureDialog;
    private static final int LOADING_SUCCESS = 2;
    private static final int LOGIN_FROM_WEB = 4;
    private static final int SCAN_QRCODE = 5;
    private static final int UPLoadImage = 6;
    private boolean mFlag;
    private String mAccountId;
    private String mSex;
    private String mMobilePhone;
    private String shareTitle;
    private String PurchaseSubOrderId = "";
    private String MedicationId = "";
    private String SupplierId = "";
    private SelectedIDcardDialog mSelectedPIDDialog;
    private String PreApplyId = "";
    private String MedicationCompanyId = "";
    private String goodID="";
    private String channerid="";
    private String ChannelName="";
    private String ChannelType="";
    private String medicalid="";
    private String ServicePackId="";

    enum SHARE_TYPE {Type_WXSceneSession, Type_WXSceneTimeline}

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOADING_SUCCESS:
                    LoadDialog.clear();
                    viewCover.setVisibility(View.GONE);
                    break;
                case UPLoadImage:
                    String strData = (String) msg.obj;
                    Log.d(TAG, strData);
                    LoadDialog.clear();
                    mFunction.onCallBack(strData);
                    break;
                default:
                    break;
            }
        }
    };
    private IWXAPI iwxapi;
    private SendGoodsEntity mSendGoodsEntity;
    private String sharedata = "";
    private String mPayType;
    private ServicePayWxInfo mWxInfo;
    private String innerLink = "";
    private String outurl = "";
    private ChooseImgEntity chooseImgEntity;
    private String Url;
    private String mName2;
    private String clinid;
    private ShareWXEntity mShareWXEntity;
    private Dialog mShareDialog;
    private View mInflateshare;
    private View mFriend;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        EventBus.getDefault().register(this);
        MyApplication.mActivities.add(WebViewActivity.this);
        ButterKnife.bind(this);
        initUrl();
        initview();
        initdata();
        initlistener();


    }

    private void initUrl() {
        if (BuildConfig.DEBUG) { //测试环境
            //判断是正式环境还是测试环境
            if (EnvironmentManager.isDebug(this)) {
                Url = "file:///android_asset/test/index.html#/";
            } else {
                Url = "file:///android_asset/online/index.html#/";
            }
        } else { //正式环境
            Url = "file:///android_asset/online/index.html#/";
        }
    }

    private void initdata() {

        sendNative();
    }

    private void initlistener() {
        ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        buShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //  NotificationUtils.showNotification(WebViewActivity.this, "新的处方审核", "消息测试");
                testBridgeWebView.loadUrl("http://172.18.30.51:8084/#/preApplyDetail?id=185&idx=0");

            }
        });

    }

    private void initview() {
        mGson = new Gson();
        Intent intent = getIntent();
        setDarkStatusWhite(true);
        LoadDialog.show(this);
        if (intent != null) {
            type = intent.getIntExtra("type", 0);
            innerLink = intent.getStringExtra("innerLink");
            mAccountId = intent.getStringExtra("AccountId");//就诊人id
            mSex = intent.getStringExtra("Sex");//就诊人id
            mMobilePhone = intent.getStringExtra("Mobile");//就诊人id
            mName2 = intent.getStringExtra("Name");//就诊人id
            clinid = intent.getStringExtra("clinid");//就诊人id
            outurl = getIntent().getStringExtra("url");
            PurchaseSubOrderId = getIntent().getStringExtra("PurchaseSubOrderId");
            MedicationId = getIntent().getStringExtra("MedicationId");
            SupplierId = getIntent().getStringExtra("SupplierId");
            PreApplyId = getIntent().getStringExtra("PreApplyId");
            MedicationCompanyId = getIntent().getStringExtra("MedicationCompanyId");
            goodID = getIntent().getStringExtra("goodID");
            channerid = getIntent().getStringExtra("channerid");
            ChannelName = getIntent().getStringExtra("ChannelName");
            ChannelType = getIntent().getStringExtra("ChannelType");
            medicalid = getIntent().getStringExtra("medicalid");
            ServicePackId = getIntent().getStringExtra("ServicePackId");

        }
        iwxapi = WXAPIFactory.createWXAPI(this, Contants.WEIXIN_APP_ID, false);
        iwxapi.handleIntent(this.getIntent(), this);

        testBridgeWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        testBridgeWebView.clearCache(true);
        testBridgeWebView.clearHistory();
        testBridgeWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        testBridgeWebView.getSettings().setSupportZoom(true);
        testBridgeWebView.getSettings().setJavaScriptEnabled(true);
        testBridgeWebView.getSettings().setBuiltInZoomControls(true);
        testBridgeWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        testBridgeWebView.getSettings().setUseWideViewPort(true);
        testBridgeWebView.getSettings().setTextZoom(100);  //消除系统大小的设置对webview字体大小的影响
        testBridgeWebView.getSettings().setDomStorageEnabled(true); //解决加载不出webview白屏问题
        testBridgeWebView.getSettings().setDatabaseEnabled(true);
        testBridgeWebView.getSettings().setAllowFileAccess(true);
        testBridgeWebView.getSettings().setAppCacheEnabled(true);
        testBridgeWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        testBridgeWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        testBridgeWebView.setBackgroundColor(0); // 设置背景色
        testBridgeWebView.setWebViewClient(new BridgeWebViewClient(testBridgeWebView) {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mHandler.sendEmptyMessageDelayed(LOADING_SUCCESS, 400);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
        switch (type) {
            case 1://申请坐诊
                mUrl = Url + "hlepCenter";

                break;
            case 2:
                mUrl = Url + "apply/applySitDr";
                break;

            case 3://申请坐诊的订单列表
                mUrl = Url + "apply/orderList";
                break;
            case 4://患者档案
                mUrl = Url + "archives";
                // setDarkStatusWhite(false);
                // setStatusBarColor(this,R.color.colorPrimary);
                break;
            case 5://分组管理
                mUrl = Url + "patient/groups/1";
                break;
            case 6://群发助手
                mUrl = Url + "archives";
                break;

            case 7://患者分组 从群发助手进来
                mUrl = Url + "patient/groups/2";
                break;
            case 8://发布公告
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "annouce";
                break;
            case 9://基础设置
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "basicSet";
                break;
            case 10://医废申请
                mUrl = Url + "medWaste/form";
                break;
            case 11://快速售药
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "directSale";
                break;
            case 12://扫描入库
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "scanCode";
                break;
            case 13://医废订单
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "medWaste/order";
                break;
            case 14://优选推荐
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "goodsIndex";
                break;
            case 15://申请处方
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "prescription/apply";
                break;
            case 16://优选推荐订单
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "prefRecommend/myRecom";
                break;
            case 17://处方申请记录
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "preApplyOrder";
                break;
            case 18://药品采集
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "homePage";
                break;

            case 19://售药记录
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "saleRecord";
                break;
            case 20://售药记录
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "myOrder";
                break;
            case 21://内部链接跳转
                if (BuildConfig.DEBUG) { //测试环境
                    //判断是正式环境还是测试环境
                    if (EnvironmentManager.isDebug(this)) {
                        mUrl = "file:///android_asset/test/index.html#" + innerLink;
                    } else {
                        mUrl = "file:///android_asset/online/index.html#" + innerLink;
                    }
                } else { //正式环境
                    mUrl = "file:///android_asset/online/index.html#" + innerLink;
                }
                break;
//            群发消息:/massMes?type=21
//            type:21-诊所专用，22-药店专用
            case 22://21-诊所专用，
                mUrl = Url + "massMes?type=21";
                break;

            case 23://22-药店专用
                mUrl = Url + "massMes?type=22";
                break;
            case 24://客服
                // setDarkStatusWhite(false);
                setStatusBarColor(this, R.color.kefu);
                mUrl = "file:///android_asset/kefu.html?userId=" + mAccountId + "&nickName=" + mName2 + "&sex=" + mSex + "&phone=" + mMobilePhone;
                // mUrl = "http://172.18.30.51:8084/#/auditor";
                break;
            case 25://25-/clinicIntro?id=诊所的机构id
                setStatusBarColor(this, R.color.colorPrimary);
                if (MyApplication.DoctorInfoEntity.getRoleType() == 4) { //药房
                    mUrl = Url + "pharmacyIndex?oId=" + MyApplication.LoginEntity.getUser().getOrgId().get(0);
                } else { //
                    mUrl = Url + "clinicIntro?id=" + MyApplication.LoginEntity.getUser().getOrgId().get(0);
                }
                break;
            case 26://重点关注
                mUrl = Url + "patient/emphasis/2";
                break;
            case 27://特色服务推荐
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "recom-all-service";
                break;
            case 28://vip预约
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "vipEntey?appToH5=1";
                break;

            case 29://三早联盟
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "threeMorning";
                break;
            case 30://服务包记录
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "service-order";
                break;

            case 31://服务包记录

                actionBarContainer.setVisibility(View.VISIBLE);
                ivLeft.setVisibility(View.VISIBLE);
                setStatusBarColor(this, R.color.colorPrimary);
                tvCenterTitle.setText("详情");
                mUrl = outurl;
                break;

            case 32://订单详情：/orderDetail?PurchaseSubOrderId
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "orderDetail?PurchaseSubOrderId=" + PurchaseSubOrderId;
                break;
            case 33://订单详情：/medicalDetail?id=${this.MedicationId}&s_id=${this.SupplierId}
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "merchantHome?SupplierId=" + SupplierId;
                break;

            case 34:// 审方
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "auditor";
                //   mUrl = "http://172.18.30.51:8084/#/auditor";
                break;
            case 35://调配核对
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "recombined";
                break;
            case 36://management 药店管理
                setStatusBarColor(this, R.color.colorPrimary);
                if (MyApplication.DoctorInfoEntity != null) {
                    mUrl = Url + "management?id=" + MyApplication.DoctorInfoEntity.getCompanyId();
                }
                break;
            case 37://prescriptePackage 处方套餐订单
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "prescriptePackage";
                break;
            case 38://prescriptePackage 申请记录详情
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "preApplyDetail?id=" + PreApplyId;
                break;
            case 39:// recombinedDetail?id=252 调配核对详情
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "recombinedDetail?id=" + PreApplyId + "&mId=" + MedicationCompanyId;
                break;
            case 40:// recombinedDetail?id=252 处方审核界面
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "auditorDetail?id=" + PreApplyId + "&mId=" + MedicationCompanyId;
                break;
            case 41:///returnVisit?mId=1064购药回访
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "returnVisit?mId=" +MyApplication.DoctorInfoEntity.getCompanyId();
                break;

            case 42:///returnVisit?mId=1064购药回访
                actionBarContainer.setVisibility(View.VISIBLE);
                ivLeft.setVisibility(View.VISIBLE);
                setStatusBarColor(this, R.color.colorPrimary);
                tvCenterTitle.setText("详情");
                mUrl = outurl;
                break;
            case 43:///商品详情
                mUrl = Url + "prefRecommend/preDetail?id=" +goodID;
                break;
            case  44://channelPage?ChannelId=44&ChannelName=%E7%83%AD%E5%8D%96%E4%BF%83%E9%94%801&ChannelType=1
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "channelPage?ChannelId=" +channerid+"&ChannelName="+ChannelName+"&ChannelType="+ChannelType;
                break;

            case  45://商品详情
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "medicalDetail?id="+medicalid+"&s_id=2";
                break;

            case  46://服务包详情
                setStatusBarColor(this, R.color.colorPrimary);
                mUrl = Url + "service-details?ServicePackId="+ServicePackId;
                break;
        }
        testBridgeWebView.loadUrl(mUrl);
        registerData();
        sendNative();

    }

    private void registerData() {

        //打电话
        testBridgeWebView.registerHandler("makeCall", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    Intent callphone = new Intent(Intent.ACTION_DIAL);
                    Uri call = Uri.parse("tel:" + data);
                    callphone.setData(call);
                    startActivity(callphone);
                } catch (Exception e) {

                }
            }
        });
        //token失效,请重新登录
        testBridgeWebView.registerHandler("tokenInvalid", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //ToastUtil.setToast("token失效,请重新登录");
                Log.i("zdp", "推出登录");
                LogOutUtil.getInstance().loginOut(WebViewActivity.this, true, 1);
            }
        });


        //H5需要登录，会请求登录接口
        testBridgeWebView.registerHandler("AppLogin", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i("zdp", "H5调用登录");
                mFunction = function;
                Intent intent = new Intent(WebViewActivity.this, LoginActivity.class);
                intent.putExtra(Contants.toLogin, Contants.From_WEB_Activity);
                startActivityForResult(intent, LOGIN_FROM_WEB);
            }
        });



        //H5主动获取登录数据
        testBridgeWebView.registerHandler("GetUserInfo", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String userInfo = "";
                if (MyApplication.isLogin) {
                    if (type == 4) { //患者档案
                        userInfo = getIntent().getStringExtra("prescriptionMessage");
                        Log.i("zdp", "H5主动获取个人数据1" + userInfo + "");
                    } else {
                        userInfo = SpUtils.getString(Contants.LoginJson);
                        Log.i("zdp", "H5主动获取个人数据2" + userInfo + "");
                    }
                    function.onCallBack(userInfo);
                } else {
                    function.onCallBack(userInfo);
                    Log.i("zdp", "H5主动获取个人数据3" + userInfo + "");
                }

            }
        });




        //获取位置
        testBridgeWebView.registerHandler("getPosition", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                Log.d(TAG, "H5打印数据" + data);
                LocationUtils.getinstanse().initlocation(WebViewActivity.this, new LocationUtils.locationStatusListener() {
                    @Override
                    public void locationSuccess(String address, String location, String province, String city, String area) {
                        //如果历史不为空，并且定位到了其他城市
                        if (TextUtils.isEmpty(area)) {
                            if (TextUtils.isEmpty(city)) {
                                function.onCallBack(province);
                            } else {
                                function.onCallBack(city);
                            }
                        } else {
                            function.onCallBack(area);
                        }

                        LocationUtils.getinstanse().stopLocation();
                    }

                    @Override
                    public void locationFailed(String data) {
                        function.onCallBack("");
                        LocationUtils.getinstanse().stopLocation();
                    }
                });
            }
        });
        //支付
        testBridgeWebView.registerHandler("payType", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                // ToastUtil.setToast("支付类型");
                Log.d("mPayType==", data);
                mPayType = data;
            }
        });


        //支付
        testBridgeWebView.registerHandler("changeStatusBarColor", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                // ToastUtil.setToast("支付类型");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setStatusBarColor(WebViewActivity.this, R.color.colorPrimary);
                    }
                });
            }
        });
        //支付
        testBridgeWebView.registerHandler("pay", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //  ToastUtil.setToast("支付");
                Log.d("data==", data);
                mFunction = function;
                WXPayEntryActivity.weixinPay(data);

            }
        });

        //支付
        testBridgeWebView.registerHandler("createWebView", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //  ToastUtil.setToast("打开外部链接" + data);
                Intent intent = new Intent(WebViewActivity.this, WebViewActivity.class);
                intent.putExtra("url", data);
                intent.putExtra(Contants.TYPE, 31);
                startActivity(intent);
            }
        });
        //预览

        testBridgeWebView.registerHandler("Preview", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d(TAG, "图片预览" + data + "");
                try {
                    ShowImageEntity mPictureList = mGson.fromJson(data, ShowImageEntity.class);
                    Intent intent = new Intent(WebViewActivity.this, PictureViewerActivity.class);
                    intent.putExtra("pic_all", (ArrayList<String>) mPictureList.getUrl());
                    intent.putExtra("pic_position", mPictureList.getPosition());
                    startActivity(intent);
                } catch (Exception e) {
                    ToastUtil.setToast("数据解析有误，无法预览");
                }

            }
        });

        //showPdfReport
        testBridgeWebView.registerHandler("showPdfReport", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    ServiceIndrocutionEntity entity = mGson.fromJson(data, ServiceIndrocutionEntity.class);
                    PDFviewUtils.getInstanse().showPDF(WebViewActivity.this, entity.getLinkUrl(), entity.getTitle());
                } catch (Exception e) {
                    ToastUtil.setToast("数据解析失败，无法查阅报告");
                }

            }
        });

        testBridgeWebView.registerHandler("ToNewLink", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                Intent intent = new Intent(WebViewActivity.this, WebViewActivity.class);
                intent.putExtra("url", data);
                intent.putExtra(Contants.TYPE, 42);
                startActivity(intent);

            }
        });
        testBridgeWebView.registerHandler("changeRemark", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                //  ToastUtil.setToast("修改患者档案" + data);
                //更新病人信息
                RxBus.get().post(Event.Chaneg_patient_info, true);
            }
        });

        testBridgeWebView.registerHandler("changeDrKey", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                //  ToastUtil.setToast("修改患者档案changeDrKey" + data);
                //更新病人信息
                RxBus.get().post(Event.Chaneg_patient_info, true);
            }
        });
        testBridgeWebView.registerHandler("saveSucess", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d(TAG, "保存数据成功");
                ToastUtil.setToast("保存数据成功saveSucess" + data);

            }
        });

        testBridgeWebView.registerHandler("toRecommendInsideLink", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d(TAG, data);
                try {
                    ServiceIndrocutionEntity entity = mGson.fromJson(data, ServiceIndrocutionEntity.class);
                    Intent intent = new Intent(WebViewActivity.this, WebViewActivity.class);
                    intent.putExtra("innerLink", entity.getLinkUrl());
                    intent.putExtra(Contants.TYPE, 21);
                    startActivity(intent);
                } catch (Exception e) {

                }
            }
        });
        testBridgeWebView.registerHandler("SendGoodsRecommend", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mSendGoodsEntity = mGson.fromJson(data, SendGoodsEntity.class);
//                GetGoodsRecommendWxShareTitle();
                sharedata = data;
                showBottomDialog();
                // ToastUtil.setToast("SendGoodsRecommend" + data);

            }
        });


        testBridgeWebView.registerHandler("drLegalize", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                // mSendGoodsEntity = mGson.fromJson(data, SendGoodsEntity.class);
//                GetGoodsRecommendWxShareTitle();
//                sharedata = data;
//                showBottomDialog();
                ToastUtil.setToast("跳转医生认证drLegalize" + data);

            }
        });
        testBridgeWebView.registerHandler("beSharePic", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                // mSendGoodsEntity = mGson.fromJson(data, SendGoodsEntity.class);
//                GetGoodsRecommendWxShareTitle();
//                sharedata = data;
//                showBottomDialog();
                //  ToastUtil.setToast("生成分享的图片" + data);
                Intent intent = new Intent(WebViewActivity.this, ShareServiceActivity.class);
                intent.putExtra("SendGoodsEntity", data);
                startActivity(intent);
            }
        });

        //回到工作台
        testBridgeWebView.registerHandler("turnWorkbench", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                // mSendGoodsEntity = mGson.fromJson(data, SendGoodsEntity.class);
//                GetGoodsRecommendWxShareTitle();
//                sharedata = data;
//                showBottomDialog();
                //  ToastUtil.setToast("回到工作台首页" + data);
                finish();
            }
        });

        testBridgeWebView.registerHandler("chooseImage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d(TAG, "上传图片" + data);
                if (data != null) {
                    mFunction = function;
                    chooseImgEntity = mGson.fromJson(data, ChooseImgEntity.class);
                    mSelectedPictureDialog = new SelectedPictureDialog(WebViewActivity.this, "first");
                    mSelectedPictureDialog.show();
                }
            }
        });

        testBridgeWebView.registerHandler("BackToIM", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                finish();
            }
        });
        testBridgeWebView.registerHandler("Back", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                finish();
            }
        });


        // 注册一个方法给JS调用：关闭网页
        testBridgeWebView.registerHandler("groups", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d("handler", "data===" + data);
                Intent intent = new Intent();
                intent.putExtra("ids", data);
                setResult(RESULT_OK, intent);
                finish();
            }
        });


        //获取二维码
        testBridgeWebView.registerHandler("scanCode", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                //开始扫描二维码，并且返回二维码数据
                mFunction = function;
                Intent intent = new Intent(WebViewActivity.this, CaptureActivity.class);
                intent.putExtra("type", type);
                startActivityForResult(intent, SCAN_QRCODE);
            }
        });
        //存储数据，获取数据


        testBridgeWebView.registerHandler("setStorage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //根据key的值，与value进行本地存储
                try {
                    KeyStorageEntity keyStorageEntity = mGson.fromJson(data, KeyStorageEntity.class);
                    SpUtils.put(keyStorageEntity.getKey(), keyStorageEntity.getValue());

                } catch (Exception e) {
                    ToastUtil.setToast("保存数据失败");
                }


            }
        });
        testBridgeWebView.registerHandler("getStorage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //根据key值直接获取数据
                String value = SpUtils.getString(data);
                KeyStorageEntity keyStorageEntity = new KeyStorageEntity();
                keyStorageEntity.setKey(data);
                keyStorageEntity.setValue(TextUtils.isEmpty(value) ? "" : value);
                String json = mGson.toJson(keyStorageEntity);
                function.onCallBack(json);

            }
        });
        //authentication 认证
        testBridgeWebView.registerHandler("toAuthenticate", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //根跳转认证
                Intent renzheng = new Intent(WebViewActivity.this, RenzhengActivity.class);
                startActivity(renzheng);
            }
        });

        //内部链接跳转
        testBridgeWebView.registerHandler("toInnerLink", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //根跳转认证
                Intent renzheng = new Intent(WebViewActivity.this, WebViewActivity.class);
                renzheng.putExtra("innerLink", data);
                renzheng.putExtra(Contants.TYPE, 21);
                startActivity(renzheng);
            }
        });

        testBridgeWebView.registerHandler("pullArea", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                Log.d(TAG, "H5打印数据" + data);
                LocationUtils.getinstanse().initlocation(WebViewActivity.this, new LocationUtils.locationStatusListener() {
                    @Override
                    public void locationSuccess(String address, String location, String province, String city, String area) {
                        //如果历史不为空，并且定位到了其他城市
                        function.onCallBack(city);
                        LocationUtils.getinstanse().stopLocation();
                    }

                    @Override
                    public void locationFailed(String data) {
                        function.onCallBack("");
                        LocationUtils.getinstanse().stopLocation();
                    }
                });
            }
        });


        //H5分享到微信或者朋友圈
        testBridgeWebView.registerHandler("ShareToWx", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

//                let url = `${introAdmin}index.html#/collegeArtDetail?aId=${this.info.ArticleId}&CKTAG=mta_share.wechat_moments`
//            let msg = {
//                title:this.info.ArticleTitle || "",
//                des:this.info.Summary || "",
//                img:this.info.ImagePath || "",
//                link:redirect + encodeURIComponent(url)
//            }
//            this.$bridge.callhandler('ShareToWx', JSON.stringify(msg))
                Log.d(TAG, "分享1" + data);

                mShareWXEntity = mGson.fromJson(data, ShareWXEntity.class);
                if (mShareWXEntity.getType() == 1) {
                    share(SHARE_TYPE.Type_WXSceneSession);
                } else {
                    showShareDialog();
                }
            }
        });


        //H5分享到微信或者朋友圈
        testBridgeWebView.registerHandler("sharePayRoll", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

//                let url = `${introAdmin}index.html#/collegeArtDetail?aId=${this.info.ArticleId}&CKTAG=mta_share.wechat_moments`
//            let msg = {
//                title:this.info.ArticleTitle || "",
//                des:this.info.Summary || "",
//                img:this.info.ImagePath || "",
//                link:redirect + encodeURIComponent(url)
//            }
//            this.$bridge.callhandler('ShareToWx', JSON.stringify(msg))
                //type:1,//1-好友，2-朋友圈，默认都可以
                Log.d(TAG, "分享2" + data);

                mShareWXEntity = mGson.fromJson(data, ShareWXEntity.class);
                if (mShareWXEntity.getType() == 1) {
                    share(SHARE_TYPE.Type_WXSceneSession);
                } else {
                    showShareDialog();
                }
            }
        });
        //支付
        testBridgeWebView.registerHandler("scanId", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                // ToastUtil.setToast("支付类型");
                Log.d("身份证识别==", data);
                //开始扫描二维码，并且返回二维码数据
                mFunction = function;
                mSelectedPIDDialog = new SelectedIDcardDialog(WebViewActivity.this, "first");
                mSelectedPIDDialog.show();

            }
        });
        //打印数据
        testBridgeWebView.registerHandler("printdata", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d(TAG, "H5打印数据" + data);
            }
        });
        //审方成功
        testBridgeWebView.registerHandler("rescriptionpReview", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d(TAG, "审方成功通知" + data);
                RxBus.get().post(Event.chufang_refresh, true);
            }
        });

        //调配
        testBridgeWebView.registerHandler("deployCheck", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d(TAG, "调配通知" + data);
                RxBus.get().post(Event.Tiaopei_refresh, true);

            }
        });


        testBridgeWebView.registerHandler("goDetailGoodsId", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d(TAG, "商品详情"+data);
            }
        });

        testBridgeWebView.registerHandler("test", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function2) {
                Log.d(TAG, "你好"+data);
                function2.onCallBack("你好");
            }
        });
    }

    public void showShareDialog() {
        mDialog = new Dialog(WebViewActivity.this, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        mInflate = LayoutInflater.from(WebViewActivity.this).inflate(R.layout.dialog_share, null);
        //初始化控件
        mFriend = mInflate.findViewById(R.id.mWechatFriend);
        mZoom = mInflate.findViewById(R.id.mWechatZone);
        mTvCancel = mInflate.findViewById(R.id.mCancel);
        mFriend.setOnClickListener(this);
        mZoom.setOnClickListener(this);
        mTvCancel.setOnClickListener(this);
        //将布局设置给Dialog
        mDialog.setContentView(mInflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 10;//设置Dialog距离底部的距离
//       将属性设置给窗体
        lp.width = LinearLayout.LayoutParams.MATCH_PARENT;
        dialogWindow.setAttributes(lp);
        mDialog.show();//显示对话框
    }

    //发送数据到H5
    public void sendNative() {


        testBridgeWebView.callHandler("test", "你好啊", new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

              Log.d("h5回调",data);
            }

        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        switch (event.getmType()) {
            case Contants.WXPAYRESULT:
                int payCode = event.getPayCode();
                if (payCode == 0) {
                    if (mFunction != null) {
                        mFunction.onCallBack("success");
                    }
//                    Intent intent = new Intent(this, PaySuccessActivity.class);
////                        intent.putExtra("payPrice", mWxInfo.getPrice());
////                        intent.putExtra("PayChannel", mWxInfo.getPayChannel());
//                    this.startActivity(intent);

                } else if (payCode == -2) {
                    if (mFunction != null) {
                        mFunction.onCallBack("cancel");
                    }
                } else {
                    if (mFunction != null) {
                        mFunction.onCallBack("fail");
                    }

//                    Intent intent = new Intent(this, PayFailActivity.class);
////                        intent.putExtra("payPrice", mWxInfo.getPrice());
////                        intent.putExtra("PayChannel", mWxInfo.getPayChannel());
////                        intent.putExtra("go_path", "webView");
//                    this.startActivity(intent);
                    mFlag = false;

                }
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    stringToBase64(mSelectedPictureDialog.getPicturePath());
                    break;
                case 3:
                    Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String path = cursor.getString(columnIndex);  //获取照片路径
                    //  uploadPicture(path);
                    stringToBase64(path);
                    break;

                case LOGIN_FROM_WEB:
                    if (mFunction != null) {
                        String loginjson2 = data.getStringExtra("loginJSON");
                        Log.i("zdp", "H5调用登录后app返回数据2" + loginjson2);
                        mFunction.onCallBack(loginjson2);
                    }
                    break;
                case SCAN_QRCODE:
                    //0--取消扫码，1--成功扫码，2--扫码失败
                    String code = data.getStringExtra("code");
                    if (TextUtils.isEmpty(code)) {
                        code = "";
                        ScanCodeEntity scanCodeEntity = new ScanCodeEntity();
                        scanCodeEntity.setResultStr(code);
                        scanCodeEntity.setType(0);
                        String jsonresult = mGson.toJson(scanCodeEntity);
                        mFunction.onCallBack(jsonresult);
                    } else {
                        ScanCodeEntity scanCodeEntity = new ScanCodeEntity();
                        scanCodeEntity.setResultStr(code);
                        scanCodeEntity.setType(1);
                        String jsonresult = mGson.toJson(scanCodeEntity);
                        mFunction.onCallBack(jsonresult);
                    }

                    break;

                case 6:
                    Log.i("zdp", mSelectedPIDDialog.getPicturePath() + "");
                    IdentificationIDcard(mSelectedPIDDialog.getPicturePath());
                    break;
                case 7:
                    Uri selectedidimg = data.getData(); //获取系统返回的照片的Uri
                    String[] filePath = {MediaStore.Images.Media.DATA};
                    Cursor cursor2 = this.getContentResolver().query(selectedidimg,
                            filePath, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor2.moveToFirst();
                    int columnIndex2 = cursor2.getColumnIndex(filePath[0]);
                    String path2 = cursor2.getString(columnIndex2);  //获取照片路径
                    //  uploadPicture(path);
                    Log.i("zdp", path2);
                    IdentificationIDcard(path2);
                    break;
            }
        }
    }

    private Dialog mDialog;
    private View mInflate;
    private LinearLayout mQrcode, mZoom, mhuanzhe;
    private TextView mTvCancel;

    public void IdentificationIDcard(String path2) {
        LoadDialog.show(this);
        //   Base64Util.imageToBase64(path);
        compressImage(path2);

    }

    public void showBottomDialog() {
        mDialog = new Dialog(WebViewActivity.this, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        mInflate = LayoutInflater.from(WebViewActivity.this).inflate(R.layout.dialog_shop_share, null);
        //初始化控件
        mQrcode = mInflate.findViewById(R.id.mqrcode);
        mhuanzhe = mInflate.findViewById(R.id.mhuanzhe);
        mTvCancel = mInflate.findViewById(R.id.mCancel);
        mQrcode.setOnClickListener(this);
        mhuanzhe.setOnClickListener(this);
        mTvCancel.setOnClickListener(this);
        //将布局设置给Dialog
        mDialog.setContentView(mInflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 10;//设置Dialog距离底部的距离
//       将属性设置给窗体
        lp.width = LinearLayout.LayoutParams.MATCH_PARENT;
        dialogWindow.setAttributes(lp);
        mDialog.show();//显示对话框
    }

    private void stringToBase64(final String path) {
        LoadDialog.show(WebViewActivity.this);
        //   Base64Util.imageToBase64(path);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                compressImage(path, emitter);
            }
        }).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "onNext" + s);
                uploadPicture(s);
            }

            @Override
            public void onError(Throwable e) {
                LoadDialog.clear();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    public void compressImage(String filePath) {
        File oldFile = new File(filePath);
        Log.d("图片压缩", "之前" + oldFile.length());

        Luban.with(this)
                .load(filePath)
                .ignoreBy(100)
                .setTargetDir(Environment.getExternalStorageDirectory().getAbsolutePath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        Log.d(TAG, Thread.currentThread() + "" + file.getAbsolutePath());
                        Log.d("图片压缩", "之后" + file.length());

                        Observable.create(new ObservableOnSubscribe<String>() {
                            @Override
                            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                                String result = IdcardRecognise.getIDNumber(file.getAbsolutePath());
                                emitter.onNext(result);
                            }
                        }).subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<String>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onNext(String s) {
                                        String mNumber = "";
                                        String sex = "";
                                        String name = "";
                                        if (mFunction != null) {
                                            try {
                                                JSONObject jsonObject = new JSONObject(s);
                                                //最外层是对象，创建对象
                                                JSONObject jsonstring = jsonObject.getJSONObject("words_result");
                                                //data对象中还是对象（carArchive），再次创建对象
                                                JSONObject numberstring = jsonstring.getJSONObject("公民身份号码");
                                                //data对象中还是对象（usedCar），再次创建对象
                                                mNumber = numberstring.getString("words");
                                                JSONObject sexstring = jsonstring.getJSONObject("性别");
                                                sex = sexstring.getString("words");
                                                JSONObject nanmestring = jsonstring.getJSONObject("姓名");
                                                name = nanmestring.getString("words");
                                                IDcardEntity entity = new IDcardEntity();
                                                entity.setIdCard(mNumber);
                                                entity.setSex(sex);
                                                entity.setName(name);
                                                String idDatajson = new Gson().toJson(entity);
                                                Log.d(TAG, "身份证数据" + idDatajson);
                                                mFunction.onCallBack(idDatajson);
                                            } catch (Exception e) {
                                                mFunction.onCallBack("");
                                            }

                                        } else {
                                            mFunction.onCallBack("识别失败");
                                        }
                                        LoadDialog.clear();
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        LoadDialog.clear();
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();

    }

    public void compressImage(String filePath, final ObservableEmitter<String> emitter) {
        File oldFile = new File(filePath);
        Log.d("图片压缩", "之前" + oldFile.length());
        Luban.with(WebViewActivity.this)
                .load(filePath)
                .ignoreBy(100)
                .setTargetDir(Environment.getExternalStorageDirectory().getAbsolutePath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        Log.d(TAG, Thread.currentThread() + "" + file.getAbsolutePath());
                        Log.d("图片压缩", "之后" + file.length());
                        emitter.onNext(Base64Util.imageToBase64(file.getAbsolutePath()));


                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();

    }

    private void uploadPicture(String base64) {
//        NetServices.Factory.getService().UploadImage(
//                base64 + ""
//                , "3"
//        ).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new BaseComPleteObserver<UploadImageEntity>(WebViewActivity.this) {
//                    @Override
//                    protected void onSuccees(BaseEntity<UploadImageEntity> t) throws Exception {
//                        Log.d(TAG, t.getData().toString());
//                        mFunction.onCallBack(t.getData().getDisplayPath());
//
//                    }
//
//                });

        String url = "";
        if (BuildConfig.DEBUG) { //测试环境
            //判断是正式环境还是测试环境
            if (EnvironmentManager.isDebug(this)) {
                url = AppConfig.TEST_URL;
            } else {
                url = AppConfig.ONLINE_URL;
            }
        } else { //正式环境
            url = AppConfig.ONLINE_URL;
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("Base64Str", base64)
                .add("", chooseImgEntity.getType() + "")
                .build();
        final Request request = new Request.Builder()
                .url(url + chooseImgEntity.getUrl())
                .post(requestBody)//默认就是GET请求，可以不写
                .header("Authorization", RetrofitFactory.getToken())
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // Log.d(TAG, "onResponse: " + response.body().string());

                String data = response.body().string();
                UploadImgSuccessEntity uploadImgSuccessEntity = mGson.fromJson(data, UploadImgSuccessEntity.class);
                UploadImgSuccessEntity.DataBean bean = uploadImgSuccessEntity.getData();
                String beanjson = mGson.toJson(bean);
                Message message = new Message();
                message.what = UPLoadImage;
                message.obj = beanjson;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        String result;
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result = "分享成功";
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "取消分享";
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "分享被拒绝";
                break;
            default:
                result = "发送返回";
                break;
        }
        Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mqrcode:
                // share(SHARE_TYPE.Type_WXSceneSession);
                Intent intent = new Intent(WebViewActivity.this, ShareGoodsActivity.class);
                intent.putExtra("SendGoodsEntity", sharedata);
                startActivity(intent);
                mDialog.dismiss();
                break;
            case R.id.mhuanzhe:
                Intent intent2 = new Intent(WebViewActivity.this, PatientListActivity.class);
                intent2.putExtra("SendGoodsEntity", sharedata);
                startActivity(intent2);
                mDialog.dismiss();
                break;

            case R.id.mCancel:
                if (mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                break;
            case R.id.mWechatFriend:
                share(SHARE_TYPE.Type_WXSceneSession);
                mDialog.dismiss();
                break;
            case R.id.mWechatZone:
                share(SHARE_TYPE.Type_WXSceneTimeline);
                mDialog.dismiss();
                break;

        }
    }

    private void share(SHARE_TYPE type) {
         /*  FileInputStream fis = null;
        try {
            fis = new FileInputStream(mSdPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (fis == null){
            return;
        }
        Bitmap thumb  = BitmapFactory.decodeStream(fis);*/

        WXWebpageObject webpageObject = new WXWebpageObject();
        // mSendGoodsEntity = mGson.fromJson(sharedata, SendGoodsEntity.class);
        if (mShareWXEntity != null) {
            shareTitle = mShareWXEntity.getTitle();
            if (!TextUtils.isEmpty(mShareWXEntity.getLink())) {
                webpageObject.webpageUrl = mShareWXEntity.getLink();
            } else {
                webpageObject.webpageUrl = "http://www.newstartclinic.com/";
            }
        } else {

            webpageObject.webpageUrl = "http://www.newstartclinic.com/";
            return;
        }
        //用WXWebpageObject对象初始化一个WXMediaMessage，天下标题，描述
        final WXMediaMessage msg = new WXMediaMessage(webpageObject);

        if (TextUtils.isEmpty(shareTitle)) {
            msg.title = "芸医生向您推荐";
        } else {
            msg.title = shareTitle;
        }
        String des = mShareWXEntity.getDes();
        msg.description = TextUtils.isEmpty(des) ? "" : des;


        if (!TextUtils.isEmpty(mShareWXEntity.getImg())) {

            //  Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
            loading(true);
            Glide.with(WebViewActivity.this)
                    .asBitmap()
                    .load(mShareWXEntity.getImg()).into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    loading(false);
                    Bitmap scaledBitmap = Bitmap.createScaledBitmap(resource, 200, 200, true);

                    msg.setThumbImage(scaledBitmap);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    switch (type) {
                        case Type_WXSceneSession:
                            req.scene = SendMessageToWX.Req.WXSceneSession;
                            break;
                        case Type_WXSceneTimeline:
                            req.scene = SendMessageToWX.Req.WXSceneTimeline;
                            break;
                    }
                    iwxapi.sendReq(req);
                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                    super.onLoadFailed(errorDrawable);
                    loading(false);
                    Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
                    msg.setThumbImage(thumb);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    switch (type) {
                        case Type_WXSceneSession:
                            req.scene = SendMessageToWX.Req.WXSceneSession;
                            break;
                        case Type_WXSceneTimeline:
                            req.scene = SendMessageToWX.Req.WXSceneTimeline;
                            break;
                    }
                    iwxapi.sendReq(req);

                }
            });

        } else {
            Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
            msg.setThumbImage(thumb);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;

            switch (type) {
                case Type_WXSceneSession:
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                    break;
                case Type_WXSceneTimeline:
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                    break;
            }
            iwxapi.sendReq(req);
        }

        //这块需要注意，图片的像素千万不要太大，不然的话会调不起来微信分享，
        //我在做的时候和我们这的UIMM说随便给我一张图，她给了我一张1024*1024的图片
        //当时也不知道什么原因，后来在我的机智之下换了一张像素小一点的图片好了！


         /* WXImageObject imageObject = new WXImageObject(bitmap);
          WXMediaMessage msg = new WXMediaMessage();
          msg.mediaObject = imageObject;*/


    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (testBridgeWebView.canGoBack()) {
                testBridgeWebView.goBack(); //goBack()表示返回WebView的上一页面
                return true;
            } else {
                finish();
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // webView清除缓存并销毁
        if (testBridgeWebView != null) {
            testBridgeWebView.stopLoading();
            testBridgeWebView.clearHistory();
            testBridgeWebView.removeAllViewsInLayout();
            testBridgeWebView.removeAllViews();
            testBridgeWebView.setWebViewClient(null);
            testBridgeWebView.destroy();
            testBridgeWebView = null;
        }
        try {
            MyApplication.remove(this);
            EventBus.getDefault().unregister(this);
        }catch (Exception e){

        }


    }

}


